<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("../../assets/img/img (3).jpg");
  background-size: cover;
}

.login-box {
  width: 500px;
  height: 350px;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 20px;
  background-color: rgba(223,212,213,0.2);
  background-size: cover;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}

.login{
  width: 50%;
  margin: 20px 130px;
  padding: 5px;
}
.el-form-item{
  display: block;
  margin: 10px 100px;
  font-weight: bolder;
}
</style>


<template>

  <div class="login-container">
    <div class="login-box">
      <h2>登录</h2>
  <el-form ref="ruleFormRef" :model="user" :rules="rules">
    <el-form-item label="用户名" prop="username">
    <el-input v-model="user.username" />
   </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="user.password" type="password" show-password/>
    </el-form-item>
  </el-form>
      <a @click="router.push('/user/resetPass')"><p style="text-align: center;margin-top: 20px">忘记密码？</p></a>
      <div class="login">
        <el-button type="primary" size="large" style="width: 110px" @click=submitUser>登录</el-button>
        <el-button type="success" size="large" style="width: 110px" @click="$router.push('/user/register')">注册</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref} from "vue";
import {userLogin} from "../../apis/UserApi.js";
import router from "../../router/router.js";
import {elPrompt} from "../../utils/elPrompt.ts";

const user=ref({
  username:'',
  password:''
})

const rules=ref({
  username:[{ validator:checkUsername,trigger: 'blur'}],
  // password:[{ validator:checkPassword,trigger: 'blur'}]
})

function checkUsername(rule,value,callback){
  const regular = /^[a-zA-Z0-9_]{4,16}$/
  if (value === ''){
    callback(new Error('请输入用户名！'))
  }else if(!regular.test(value)){
    callback(new Error('用户名长度为4-16位！且由字母、数字或下划线组成！'))
  }else{
    callback()
  }
}

function checkPassword(rule,value,callback){
  const regular = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d!@#$%^&*]{6,}$/;
  if (value === ''){
    callback(new Error('请输入密码！'))
  }else if(!regular.test(value)){
    callback(new Error('至少6个字符 包含至少一个大写字母、一个小写字母和一个数字 可以包含特殊字符（例如：!@#$%^&*）'))
  }else{
    callback()
  }
}

function submitUser(){
  userLogin(user.value.username,user.value.password,(result)=>{
    if (result.status === 200){
      localStorage.setItem("token",result.data)
      elPrompt("登录成功！", "success")
      router.push('/')
    }else{
      elPrompt(result.message,"error")
    }
  })
}

</script>